package com.czy.owner.ui.archive;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.czy.owner.R;
import com.czy.owner.adapter.ArchiveGarageAdapter;
import com.czy.owner.api.CarParameterGetApi;
import com.czy.owner.api.OwnerCarApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.garage.EditCarActivity;
import com.czy.owner.ui.garage.MyGarageActivity;
import com.czy.owner.ui.garage.PickBrandActivity;
import com.czy.owner.ui.illegalquery.IllegalQueryActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.UniversalDialog;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lib.fancycoverflow.FancyCoverFlow;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * Created by King on 2017-05-10
 * 爱车档案
 */

public class CarDossierFragment extends BaseFragment {
    @BindView(R.id.linear_layout_top_view)
    LinearLayout llTop;

    @BindView(R.id.btn_title_left)
    Button btnTitleLeft;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.fcf_archive_garage_list)
    FancyCoverFlow fcfGarage;

    @BindView(R.id.rl_dossier_maintenance)
    RelativeLayout rlMaintenance;
    @BindView(R.id.rl_dossier_detection)
    RelativeLayout rlDetection;
    @BindView(R.id.rl_dossier_insurance)
    RelativeLayout rlInsurance;

    @BindView(R.id.rl_car_paramter)
    RelativeLayout rlCarParamter;
    @BindView(R.id.tv_dossier_insurance_tip)
    TextView tvInsuranceTip;
    @BindView(R.id.ll_car_parameter_gearbox)
    LinearLayout llParameterGearbox;
    @BindView(R.id.ll_car_parameter_antifreeze)
    LinearLayout llParameterAntifreeze;
    @BindView(R.id.ll_car_parameter_tyre)
    LinearLayout llParameterTyre;
    @BindView(R.id.ll_car_parameter_wiper)
    LinearLayout llParameterWiper;

    @BindView(R.id.tv_car_parameter_gearbox)
    TextView tvParameterGearbox;
    @BindView(R.id.tv_car_parameter_antifreeze)
    TextView tvParameterAntifreeze;
    @BindView(R.id.tv_car_parameter_tyre)
    TextView tvParameterTyre;
    @BindView(R.id.tv_car_parameter_wiper)
    TextView tvParameterWiper;

    @BindView(R.id.tv_car_parameter_gearbox_tips)
    TextView tvParameterGearboxTips;
    @BindView(R.id.tv_car_parameter_antifreeze_tips)
    TextView tvParameterAntifreezeTips;
    @BindView(R.id.tv_car_parameter_tyre_tips)
    TextView tvParameterTyreTips;
    @BindView(R.id.tv_car_parameter_wiper_tips)
    TextView tvParameterWiperTips;

    @BindView(R.id.tv_car_parameter_gearbox_hint)
    TextView tvParameterGearboxHint;
    @BindView(R.id.tv_car_parameter_antifreeze_hint)
    TextView tvParameterAntifreezeHint;
    @BindView(R.id.tv_car_parameter_tyre_hint)
    TextView tvParameterTyreHint;
    @BindView(R.id.tv_car_parameter_wiper_hint)
    TextView tvParameterWiperHint;


    @BindView(R.id.rl_dossier_Illegal)
    RelativeLayout rlDossierIllegal;

    //2017-8-24wangyang新增
    @BindView(R.id.ll_car_parameter_year_check)
    LinearLayout llCarParameterYearCheck; //年检到期日
    @BindView(R.id.tv_car_parameter_year_check)
    TextView tvCarParameterYearCheck;
    @BindView(R.id.tv_car_parameter_year_check_tips)
    TextView tvCarParameterYearCheckTips;
    @BindView(R.id.tv_car_parameter_year_check_hint)
    TextView tvCarParameterYearCheckHint;


    private int currentCarIndex = 0;
    private boolean isFrist = true;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_car_dossier;
    }

    @Override
    protected void initInjector() {
    }

    @Override
    protected void initViews() {
    }

    @Override
    protected void updateViews() {
        boolean hasArgument = getArguments() != null && getArguments().containsKey("showBack");
        if (hasArgument && getArguments().getInt("showBack") == 0) {
            hideTitleLeftButton();
        } else {
            llTop.setVisibility(View.GONE);
        }

        initListener();
    }

    public void hideTitleLeftButton() {
        btnTitleLeft.setVisibility(View.GONE);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //initListener();
        // TODO 获取车库车辆信息
        //initCarInfoData(true);
        //showCarArchive();
    }

    private void initListener() {
        btnTitleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        tvTitleRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(mContext, "管理车型", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(getContext(), MyGarageActivity.class));
            }
        });
        //TODO 养车记录
        rlMaintenance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkCarsNumber()) {
                    startActivity(new Intent(getContext(), MaintenanceRecordActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, UserHelper.getInstance().getCarInfoList().get(currentCarIndex)));
                }
            }
        });
        rlDetection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkCarsNumber()) {
                    startActivity(new Intent(getContext(), MaintenanceDetectionActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, UserHelper.getInstance().getCarInfoList().get(currentCarIndex)));
                }
            }
        });
        rlInsurance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkCarsNumber()) {
                    startActivity(new Intent(getContext(), InsuranceSettingActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, UserHelper.getInstance().getCarInfoList().get(currentCarIndex)));
                }
            }
        });

        rlDossierIllegal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), SelectIllegalQueryActivity.class));
            }
        });
        View.OnClickListener parameterListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkCarsNumber()) {
                    startActivity(new Intent(getContext(), CarParameterActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, UserHelper.getInstance().getCarInfoList().get(currentCarIndex)));
                }
            }
        };


//        llParameterGearbox.setOnClickListener(parameterListener);
        rlCarParamter.setOnClickListener(parameterListener);
//        llParameterAntifreeze.setOnClickListener(parameterListener);
//        llParameterTyre.setOnClickListener(parameterListener);
//        llParameterWiper.setOnClickListener(parameterListener);
//        llCarParameterYearCheck.setOnClickListener(parameterListener);

    }

    private boolean checkCarsNumber() {
        return checkCarsNumber(true);
    }

    /**
     * @return 检测车库汽车数量 为0时跳转至添加车辆 ,大于0时 返回true
     */
    private boolean checkCarsNumber(boolean isClick) {
        if (UserHelper.getInstance().getDefaultCarIndex() == 0 && UserHelper.getInstance().getDefaultCar() == null) {
            Toast.makeText(mContext, "车辆信息加载中,请稍候!", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (UserHelper.getInstance().getDefaultCarIndex() == -1) {
            if (isClick) {
                PhoneUtils.ShowToastMessage(getContext(), "请添加车辆!");
                Intent intent = new Intent();
                intent.setClass(getContext(), PickBrandActivity.class);
                // 新增车辆无需立即返回
                intent.putExtra(PickBrandActivity.START_FLAG, 0);
                startActivityForResult(intent, 1);
            }
            return false;
        }
        return true;
    }

    private void initCarInfoData() {
        OwnerCarApi ownerCarApi = new OwnerCarApi(new HttpOnNextListener<List<CarInfo>>() {
            @Override
            public void onNext(List<CarInfo> o) {
                showCarInfo(o);
            }

            @Override
            public void onCacheNext(String string) {
                super.onCacheNext(string);
                BaseResultEntity<List<CarInfo>> carInfoData = new GsonBuilder().create().fromJson(string, new TypeToken<BaseResultEntity<List<CarInfo>>>() {
                }.getType());
                showCarInfo(carInfoData.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                Toast.makeText(mContext, "CarDossierFragment get dossiers error!", Toast.LENGTH_SHORT).show();
            }
        }, (RxAppCompatActivity) getContext());
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSession(getContext()));
        ownerCarApi.setMap(requestMap);
        HttpManager.getInstance().doHttpDeal(ownerCarApi);
    }

    private void showCarInfo(List<CarInfo> list) {
        UserHelper.getInstance().setCarInfoList(list);
        if (isFrist && currentCarIndex == 0) {
            currentCarIndex = UserHelper.getInstance().getDefaultCarIndex();
        }
        if (isFrist)
            isFrist = false;
        if (checkCarsNumber(false)) {
            ArchiveGarageAdapter mGarageAdapter = new ArchiveGarageAdapter(getContext(), UserHelper.getInstance().getCarInfoList(), PhoneUtils.dip2px(getContext(), 160), PhoneUtils.dip2px(getContext(), 106));
            fcfGarage.setAdapter(mGarageAdapter);
            if (currentCarIndex >= UserHelper.getInstance().getCarInfoList().size()) {
                currentCarIndex = UserHelper.getInstance().getDefaultCarIndex();
            }
            fcfGarage.setSelection(currentCarIndex);
            fcfGarage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view,
                                           int position, long id) {
                    currentCarIndex = position;
                    //SharedPreferencesUtils.setParam(mContext, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_CURRENT_CAR, currentCarIndex);
                    showCarParameter();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            fcfGarage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(getContext(), EditCarActivity.class);
                    intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.MODIFY);
                    intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, UserHelper.getInstance().getCarInfoList().get(currentCarIndex));
                    startActivityForResult(intent, 1);
                }
            });
        } else {
            //Toast.makeText(mContext, "CarDossierFragment get mCarInfoList:" + (mCarInfoList == null), Toast.LENGTH_SHORT).show();
            new UniversalDialog(getActivity()).builder().setTitle("提示")
                    .setCancelable(false)
                    .setMsg("没有发现车辆信息,是否添加车辆")
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setClass(getContext(), PickBrandActivity.class);
                            // 新增车辆无需立即返回
                            intent.putExtra(PickBrandActivity.START_FLAG, 0);
                            startActivityForResult(intent, 1);
                        }
                    }).setNegativeButton("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean hasArgument = getArguments() != null && getArguments().containsKey("showBack");
                    if (hasArgument && getArguments().getInt("showBack") == 0) {
                        //TODO 切换到其他TAB页
                        RxBus.getDefault().post(Constants.RXBUS_CODE_SWITCH_MAIN_TAB, new CommonEvent(0));
                    } else {
                        getActivity().finish();
                    }
                }
            }).show();
        }

    }

    @Deprecated
    private void initCarParameter() {
        CarParameterGetApi parameterGetApi = new CarParameterGetApi(new HttpOnNextListener<CarInfo>() {
            @Override
            public void onNext(CarInfo o) {

            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                Toast.makeText(mContext, "CarDossierFragment get dossiers error!", Toast.LENGTH_SHORT).show();
            }
        }, (RxAppCompatActivity) getContext());
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(getContext()).getSession());
        requestMap.put("ownerCarId", UserHelper.getInstance().getCarInfoList().get(currentCarIndex).getOwnerCarId());
        parameterGetApi.setMap(requestMap);
        HttpManager.getInstance().doHttpDeal(parameterGetApi);
    }


    private void showCarParameter() {
        CarInfo mCarInfo = UserHelper.getInstance().getCarInfoList().get(currentCarIndex);
        if (mCarInfo.getNextInsuranceTime() == 0) {
            tvInsuranceTip.setText("");
        } else {
            Calendar nowCal = Calendar.getInstance();
            nowCal.setTimeInMillis(System.currentTimeMillis());

            Calendar preCal = Calendar.getInstance();
            preCal.setTimeInMillis(mCarInfo.getNextInsuranceTime());

            if (nowCal.get(Calendar.YEAR) == preCal.get(Calendar.YEAR)) {
                int diffDay = preCal.get(Calendar.DAY_OF_YEAR) - nowCal.get(Calendar.DAY_OF_YEAR);
                if (diffDay == 0) {
                    tvInsuranceTip.setText(Html.fromHtml("<font color='#CF0537'>今天</font>到期"));
                } else if (diffDay < 0) {
                    tvInsuranceTip.setText(Html.fromHtml("<font color='#CF0537'>已过期</font>"));
                } else if (diffDay == 1) {
                    tvInsuranceTip.setText(Html.fromHtml("<font color='#CF0537'>明天</font>到期"));
                } else {
                    tvInsuranceTip.setText(Html.fromHtml("还有<font color='#CF0537'>" + diffDay + "</font>天到期"));
                }
            } else {
                long diffTimeMillis = mCarInfo.getNextInsuranceTime() - System.currentTimeMillis();
                if (diffTimeMillis > 0) {
                    MyLog.e("yang", "***********" + (int) (diffTimeMillis / (3600 * 24 * 1000)));
                    tvInsuranceTip.setText(Html.fromHtml("还有<font color='#CF0537'>" + (int) (diffTimeMillis / (3600 * 24 * 1000)) + "</font>天到期"));
                } else {
                    tvInsuranceTip.setText(Html.fromHtml("<font color='#CF0537'>已过期</font>"));
                }
            }
        }

        //"transmissionType": "变速箱类型",
        if (TextUtils.isEmpty(mCarInfo.getTransmissionType())) {
            tvParameterGearbox.setVisibility(View.GONE);
            tvParameterGearboxTips.setVisibility(View.GONE);
            tvParameterGearboxHint.setVisibility(View.VISIBLE);
        } else {
            tvParameterGearbox.setVisibility(View.VISIBLE);
            tvParameterGearboxTips.setVisibility(View.VISIBLE);
            tvParameterGearboxHint.setVisibility(View.GONE);
            tvParameterGearbox.setText(mCarInfo.getTransmissionType());
        }

        //"engineModel": "发动机型号",
        if (TextUtils.isEmpty(mCarInfo.getEngineModel())) {
//            tvParameterEngine.setVisibility(View.GONE);
//            tvParameterEngineTips.setVisibility(View.GONE);
//            tvParameterEngineHint.setVisibility(View.VISIBLE);
        } else {
//            tvParameterEngine.setVisibility(View.VISIBLE);
//            tvParameterEngineTips.setVisibility(View.VISIBLE);
//            tvParameterEngineHint.setVisibility(View.GONE);
//            tvParameterEngine.setText(mCarInfo.getEngineModel());
        }

        //       "antifreezeColor": 防冻液颜色 ,
        if (TextUtils.isEmpty(mCarInfo.getAntifreezeColor())) {
            tvParameterAntifreeze.setVisibility(View.GONE);
            tvParameterAntifreezeTips.setVisibility(View.GONE);
            tvParameterAntifreezeHint.setVisibility(View.VISIBLE);
        } else {
            tvParameterAntifreeze.setVisibility(View.VISIBLE);
            tvParameterAntifreezeTips.setVisibility(View.VISIBLE);
            tvParameterAntifreezeHint.setVisibility(View.GONE);
            tvParameterAntifreeze.setText(mCarInfo.getAntifreezeColor());
        }

        //       "tireSpec": "轮胎规格",
        if (TextUtils.isEmpty(mCarInfo.getTireSpec())) {
            tvParameterTyre.setVisibility(View.GONE);
            tvParameterTyreTips.setVisibility(View.GONE);
            tvParameterTyreHint.setVisibility(View.VISIBLE);
        } else {
            tvParameterTyre.setVisibility(View.VISIBLE);
            tvParameterTyreTips.setVisibility(View.VISIBLE);
            tvParameterTyreHint.setVisibility(View.GONE);
            tvParameterTyre.setText(mCarInfo.getTireSpec());
        }

        //"wiperType": "雨刮器类型",
        if (TextUtils.isEmpty(mCarInfo.getWiperType())) {
            tvParameterWiper.setVisibility(View.GONE);
            tvParameterWiperTips.setVisibility(View.GONE);
            tvParameterWiperHint.setVisibility(View.VISIBLE);
        } else {
            tvParameterWiper.setVisibility(View.VISIBLE);
            tvParameterWiperTips.setVisibility(View.VISIBLE);
            tvParameterWiperHint.setVisibility(View.GONE);
            tvParameterWiper.setText(mCarInfo.getWiperType());
        }


        // nextInspectionTime 年检到期日期
        if (mCarInfo.getNextInspectionTime() == 0) {
            tvCarParameterYearCheck.setVisibility(View.GONE);
            tvCarParameterYearCheckHint.setVisibility(View.VISIBLE);
        } else {
            tvCarParameterYearCheck.setVisibility(View.VISIBLE);
            tvCarParameterYearCheckHint.setVisibility(View.VISIBLE);
            tvCarParameterYearCheck.setText(TimeUtils.formatTimeDifference3(mCarInfo.getNextInspectionTime()) + "");
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        initCarInfoData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            // TODO 车辆添加成功返回
            //initCarInfoData();
        }
    }
}
